<template>
    
    <!-- 组件的模板 -->
    <div class="page__bd">
        <div class="weui-search-bar" id="searchBar">
            <form class="weui-search-bar__form">
                <div class="weui-search-bar__box">
                    <i class="weui-icon-search"></i>
                    <input type="search" class="weui-search-bar__input" id="searchInput" placeholder="搜索" required="">
                    <a href="javascript:" class="weui-icon-clear" id="searchClear"></a>
                </div>
                <label class="weui-search-bar__label" id="searchText" style="transform-origin: 0px 0px 0px; opacity: 1; transform: scale(1, 1);" @click="toSearch">
                    <i class="weui-icon-search"></i>
                    <span>搜索</span>
                </label>
            </form>
        </div>
    </div>
    <div class="page user-select multi-select">
      <scroller :lock-y="true" v-ref:scrollerdom>
        <div class="mod-crumbs bg-color scroller-wrap" v-show="hierarchyList.length>1">
          <template v-for="(index,hierarchy) in hierarchyList">
                <template v-if="index<(hierarchyList.length-1)">
                    <a class="nav-item" @click="stepHierarchy(index)">{{hierarchy.name}}</a>
                    <span class="arrow nav-item">&gt;</span>
                </template>
                <template v-if="index==(hierarchyList.length-1)">
                    <em class="nav-item">{{hierarchy.name}}</em>
                </template>
          </template> 
        </div>
      </scroller>
     
       <!-- <ul class="list com-border-top com-border-bottom">
          <li class="weui-cells_checkbox">
              <label class="touch" for="ss">
                  <input type="checkbox" class="weui-check" name="ss" id="ss" :checked="isSelectAll"  @click="selectAll($event)">
                  <i class="weui-icon-checked"></i>
                  <div class="info com-border-bottom">
                      <p class="title">全选</p>
                  </div>
              </label>
          </li> 
      </ul> -->

       <ul class="list com-border-top com-border-bottom" style="margin-top:0" :style="isIphoneX?'margin-bottom: 37px;':''">
            <li class="weui-cells_checkbox has-hierarchy"  v-for='group in grouplist'>
                <label class="touch" for="{{group.id}}">
                     <input value="{{group.id}}" 
                             v-model="selectGroupList" 
                             type="checkbox" 
                             class="weui-check" 
                             name="checkbox1" 
                             id="{{group.id}}"
                             @change="selectGroup(group,$event)"
                      >
                    <i class="weui-icon-checked"></i>
                    <div class="info com-border-bottom">
                        <!-- <p class="title">{{group.name}}</p> -->
                        <p class="title" :class="{'no-nextGroup': !(group.children.length)}">{{group.name}}</p>
                    </div>
                </label>
                <div class="hierarchy" :class="{'disabled':selectGroupList.indexOf(group.id+'')>-1}" v-show="group.children.length" @click="stepNext(group.id)">下级</div>
            </li>
      </ul>
<!-- 
      <div class="count bg-color com-border-top">
        <span class="num">已选择：<em>{{selectGroupList.length}}个小组</em></span>
            <a class="mod-btn-s-1" @click="submitResult">确定</a>
      </div> -->
      <!-- <div class="count bg-color com-border-top weui-cells_checkbox">
            <label for="sa">
                <input type="checkbox" class="weui-check" name="select-all" id="sa" :checked="isSelectAll"  @click="selectAll($event)">
                <i class="weui-icon-checked"></i><span>全选</span>                
            </label>
            <span class="num">已选择：<em>{{selectGroupList.length}}个小组</em></span>
            <a class="mod-btn-s-1" v-if="selectGroupList.length == 0" style="background: rgb(206, 204, 200)">确定</a>
            <a class="mod-btn-s-1" @click="submitResult" v-else>确定</a>
        </div> -->

        <div class="count bg-color com-border-top weui-cells_checkbox" :style="isIphoneX?'height: 75px;':''" v-if="grouplist.length">
            <label for="sa">
                <input type="checkbox" class="weui-check" name="select-all" id="sa" :checked="isSelectAll"  @click="selectAll($event)">
                <i class="weui-icon-checked"></i><span>全选</span>                
            </label>
            <span class="num">已选择：<em>{{selectGroupList.length}}个小组</em></span>
            <!-- <a class="mod-btn-s-1 disabled" v-if="selectGroupList.length == 0">确定</a> -->
            <a class="mod-btn-s-1" @click="submitResult" href="javascript:;">确定</a>
      </div>
    </div>
</template>

<script>
    let pageDate = {}
    let webViewID = ''
    /**
     *  引入工具类库 或 Native API
     *  example : import widget from 'gapi/widget'
     */
    import widget from 'gapi/widget'
    import cache from 'gapi/cache.js'
    import commonPage from 'clientApi/commonPage.js'
    import * as util from 'js/util.js'
    import GroupUtil from 'js/GroupUtil.js'
    import Scroller from 'vux/dist/components/scroller'
    /**
     *  引入组件 以及 组件接口(Action)
     *  example : import Somecomponents from 'components/Somecomponents/Somecomponents'
     */

    /**
     *  组件实例对象
     */
    export default {
        components: {
          Scroller
        },
        data: function(){
            return{
                group:{},
                hierarchyList:[],
                selectGroupList:[],
                grouplist:[],
                cacheGroupList:[]
            }
        },
        watch: {
          'hierarchyList': function(){
            let allWidth = 0
            this.$nextTick(function () {
              if($('.scroller-wrap .nav-item').length){
                $('.scroller-wrap .nav-item').each(function(i, o){
                  if(o.tagName.toLowerCase() == 'a'){
                    allWidth += (parseInt(o.offsetWidth) + 16)
                  }else{
                    allWidth += parseInt(o.offsetWidth)
                  }
                })
                allWidth += 30
                $('.scroller-wrap').width(allWidth + 'px')

                this.$refs.scrollerdom.reset()
              }
            })
          }
        },
        computed: {
            isSelectAll (){
                 let result = false
                 if(this.grouplist.length){
                    result = true
                    this.grouplist.forEach((item)=>{
                      if(this.selectGroupList.indexOf(item.id+'')==-1){
                            // this.selectGroupList = this.removeArrarItem(this.selectGroupList,[this.id])
                            result = false
                      }
                    })
                 }
                return result
            },
            isIphoneX: function(){
                return util.isIphoneX()
            }
        },
        vuex: {
            getters: {

            },
            actions: {

            }
        },
        methods: {
            /**
             * 初始化
             * @method init
             * @public
             * @return {Null} void
             */
            init (){
               cache.getMemoryCache('participantGroup', (data) => {
                console.log(data)
                    if(data){
                        this.selectGroupList = data
                        // data.forEach((item) => {   // 修改之后
                        //   this.selectGroupList.forEach( (memberItem) => {
                        //     if(memberItem.id != item.id){
                        //       this.selectGroupList.push(item)
                        //     }
                        //   })
                        // })
                    } 
                })
                cache.getCache('KqCacheMessge',(data)=>{
                    pageDate.project_id = data.project_id
                    pageDate.team_id = data.team_id
                    pageDate.user_id = data.user_id

                    this.id = util.getUrddataString('id')
                    if(this.id){
                          cache.getMemoryCache('cacheGroupList', (data) => {
                              if(data){
                                  this.group = new GroupUtil(data)
                                  this.showGroup(this.id,this.group.group)
                              }
                          })
                    }else{
                          this.getGroupList()
                    }
                })
                commonPage.getWebViewID((data)=>{
                    webViewID = data
                })
            },
            /**
             * 当选中小组时，判断该小组的子小组是否被选中，若有被选中的子小组，则清除掉
             * @param  {[type]} group [description]
             * @param  {[type]} event [description]
             * @return {[type]}       [description]
             */
            selectGroup(group,event){
                  let list = []
                  let id = group.id
                  let label = event.target.checked
                  let getChildren = (group)=>{
                      group.forEach((item)=>{
                          if(this.selectGroupList.indexOf(item.id+'')>-1){
                              list.push(item.id+'')
                          }
                          if(item.children.length){
                              getChildren(item.children)
                          }
                      })
                  }
                  if(label&&group.children.length){
                      getChildren(group.children)
                      this.selectGroupList = this.group.removeArrarItem(this.selectGroupList,list)
                  }
            },
            //全选按钮
            selectAll(event){
                let label = event.target.checked
                let list = []
                this.grouplist.forEach((item)=>{
                    list.push(item.id+'')
                    this.selectGroup(item,event)
                    // this.group.setGroupById(item.id,label)
                })
                if(label){
                    this.selectGroupList = this.group.addArrarItem(this.selectGroupList,list)
                }else{
                    this.selectGroupList = this.group.removeArrarItem(this.selectGroupList,list)
                }
                // this.selectGroupList = this.group.getSelectedGroup()
            },

            /**
             * 跳转下一级
             * @param  {[type]}
             * @return {[type]}
             */
            stepNext(id){
                if(this.selectGroupList.indexOf(id+'') == -1){
                    cache.setMemoryCache('participantGroup',this.selectGroupList)
                    window.location.href="dmsaas://KaoqinAddGroup?urdData="+encodeURIComponent(`id=${id}`)
                    // window.location.href="http://192.168.45.155:8000/app/yy_kqgroupselect/yy_kqgroupselect.html?urdData="+encodeURIComponent(`id=${id}`)
                }
            },
            /**
             * 点击对应层级 
             * 
             * @return {[type]}
             */
            stepHierarchy(index){
                let leg = this.hierarchyList.length-1
                if(index<leg){
                    // commonPage.goBack(1,{'goBackKey':'index','value':index,'participantGroup':this.selectGroupList})
                    cache.getMemoryCache('webViewID'+index,(data)=>{
                        if(data){
                           commonPage.goBack(1,{'key':'participantGroup','value':this.selectGroupList},data.webViewID)
                        } 
                    })
                }
            },
            // 当前页面数据处理
            showGroup(id,list){
                  list.some((item)=>{
                    if(item.id==id){
                        this.hierarchyList = item.path
                        this.grouplist = item.children
                        let len = this.hierarchyList.length-1
                        cache.setMemoryCache('webViewID'+len,{'webViewID':webViewID})//保存当前页面唯一标识，点击面包屑使用
                        return true
                    }else{
                        this.showGroup(id,item.children)
                    }
                })
            },
            // 获取小组列表
            getGroupList(){
                commonPage.loadPageStatus('loading')
                util.ajax({
                    url: '/group/node_tree',
                    data: {
                        team_id:pageDate.team_id,
                        project_id: pageDate.project_id
                    },
                    success: (res) => {
                        console.log(res)
                        // res = JSON.parse(res) 
                        commonPage.loadPageStatus('loadSuccess') 
                        if(res&&res.errno==0){
                            this.cacheGroupList = res.data
                            this.group = new GroupUtil(this.cacheGroupList)
                            this.hierarchyList = [{'id':'all','name':'全部'}]
                            this.grouplist = this.group.group
                            let allGroupList = this.group.formatGroup(this.group.group)
                            cache.setMemoryCache('allGroupList',allGroupList)
                            cache.setMemoryCache('cacheGroupList',this.cacheGroupList)
                            cache.setMemoryCache('webViewID0',{'webViewID':webViewID})
                        }else if(res.errmsg){
                             widget.toast(res.errmsg)
                        }else{
                           widget.toast('数据获取失败')
                        }
                        
                    },
                    error: (xhr, status) => {
                         commonPage.loadPageStatus('loadSuccess')
                         widget.toast('服务器异常')
                    },
                    noNetwork: () => {
                        commonPage.loadPageStatus('loadSuccess')
                        widget.toast('网络连接失败，请检查网络')
                    }
                })
            },
            //提交
            submitResult() {
                console.log(this.selectGroupList)
                var participantGroup = this.selectGroupList
                let GroupNameList = []
                this.selectGroupList.forEach((selG) => {
                  this.group.formatGroup(this.group.group).forEach((allG) => {
                    if(selG == allG.id){
                      GroupNameList.push(allG.name)
                    }
                  })
                })
                cache.getMemoryCache('webViewID',(data)=>{
                    if(data){
                      commonPage.goBack(1,{'goBackKey':'submit','key':'participantGroup','value':participantGroup,name: GroupNameList},data.webViewID)
                    }
                })
            },
            /**
             * 跳转搜索页
             * @return {}
             */
            toSearch(){
                cache.setMemoryCache('participantGroup',this.selectGroupList)
                window.location.href="dmsaas://KaoqinGroupSearch"
            }
        },
        created(){
            this.init()
            window.loadData = (data)=>{
              console.log(data)
                if(data&&data.key == 'participantGroup'){
                    this.selectGroupList = data.value
                }
            }
        }
        
    }

    
</script>

<!-- CSS 样式 -->
<style src="../../node_modules/weui/dist/style/weui.css"></style>
<style src="../../static/css/common.css"></style>
<style src="../../static/css/user-list.css"></style>
<style>
  .scroller-wrap .nav-item{
      float: left;
    }
  .mod-crumbs .arrow.nav-item{
    margin: 18px 8px;
  }
  .xs-container{
    background: #fff;
  }
</style>
